//
//  ViewController.swift
//  UTSNetwork
//
//  Created by jack on 08/02/2024.
//  Copyright (c) 2024 jack. All rights reserved.
//

import UIKit
import UTSNetwork
import Alamofire

class ViewController: UIViewController {
    
    var mSession: Session?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let sss = ""
        let resultString = sss.replacingOccurrences(of: "stringToReplace", with: "replacementString")

        
        let filePath = Bundle.main.path(forResource: "cer", ofType: "cer")!
        
        let cerStrPath = Bundle.main.path(forResource: "cer", ofType: "txt")!
        var cerStr = try! NSString(contentsOfFile: cerStrPath, encoding: 0)
        
//        var cerStr: NSString = "-----BEGIN CERTIFICATE-----\n" +
//        "MIIDazCCAlOgAwIBAgIUHnAowRXnRNGbDV/PRnfx52tPObkwDQYJKoZIhvcNAQEL\n" +
//        "BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM\n" +
//        "GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDA4MDgwMjQ5MDVaFw0yNTA4\n" +
//        "MDgwMjQ5MDVaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw\n" +
//        "HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB\n" +
//                "AQUAA4IBDwAwggEKAoIBAQCwXACiypYBZEZp5gWR1mk3Bt9cu9g5XO8nJNo//Cl0\n" +
//                "Ci6CDN3tpK6j7uoQb/RtrzHESO2POXFglBtE9ST6zsBA+O5582yhrr4YpMhHtIxk\n" +
//                "tk12hiHL6y8Z1OQTgrKFSrx9g84HSasJEPjALxgMOzRQP8DtFwGqHEoRB3KpX5f/\n" +
//                "ZzADojhMznPEpkUOYV+WdiQw4s0GL4UZOgOGYkf8vI38r9afTellpI+t6m7+fpQy\n" +
//                "6fbcnMeppFCYhwxilN6l0wxjStz4r2X4Aw9EVsdyw9QBYbyGIVkHkcPRqrVOXmRz\n" +
//                "yh/+TozrpZyxkYIc9nE2AUQ1yPNe2LbNiViQa/AJhYvpAgMBAAGjUzBRMB0GA1Ud\n" +
//                "DgQWBBRgyKsycZ/V96snUIfptYE1/ekuozAfBgNVHSMEGDAWgBRgyKsycZ/V96sn\n" +
//                "UIfptYE1/ekuozAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQA8\n" +
//                "8as8JjVcMr8RmgPco4MZ4PrORbhpaChiuGrkXyN5cNcLgHjH/+Le5A/f6b9MKuHQ\n" +
//                "dKBoSyqpJy/Ef6AM4Bvdr0aSUDesHjdLkEu6VfAFYdAZnCNqq09xR6zADtnC+KvE\n" +
//                "Lxm3U5bfIiLFkVrckJi3EJkuNf1Acq/M/QDyJ3dByaJpqoiXwhCcJeF1vGYy4NRp\n" +
//                "HVH4QrvJxLhnBSuyLXb9QfyUzTbrlsYIZjWgyn3uG8uR94WnezEMhjYOTjsCyv2v\n" +
//               "2NcjE1zv6BdrM3PBEIMHE+PRgER7itnYMhkRSuZayKdGqYfuuH6qmmFOGckvzclQ\n" +
//                "voqmSl76Z8CHZCdFWkt5\n" +
//        "-----END CERTIFICATE-----"
//
        cerStr =  cerStr.replacingOccurrences(of: "\n", with: "") as NSString
        cerStr =  cerStr.replacingOccurrences(of: "-----BEGIN CERTIFICATE-----", with: "") as NSString
        cerStr =  cerStr.replacingOccurrences(of: "-----END CERTIFICATE-----", with: "") as NSString
        
        var data = try! Data(contentsOf: URL(fileURLWithPath: filePath))
        
        data = Data(base64Encoded: cerStr as String, options: .ignoreUnknownCharacters)!
//        data = cerStr.data(using: .utf8)!
        
        let cfData = data as CFData
        let certificate: SecCertificate = SecCertificateCreateWithData(nil, cfData)!
        var certificates: [SecCertificate] = [certificate]
//        certificates.removeAll()
        let urlStr = "https://172.16.11.23"
         let tempHost =  NSURL(string: urlStr)?.host

        let host = tempHost!
        let pinnedEva = PinnedCertificatesTrustEvaluator(certificates: certificates, acceptSelfSignedCertificates: true, performDefaultValidation: false, validateHost: false)

        var publicKeyArray:[SecKey] = []
        if let key = certificate.af.publicKey {
            publicKeyArray.append(key)
        }
        
       
       
       let publicEva = PublicKeysTrustEvaluator(keys: publicKeyArray, performDefaultValidation: false, validateHost: false)
        
        let disabledEva = DisabledTrustEvaluator()
        let manager = ServerTrustManager(evaluators: [host: disabledEva])
        let configuration = URLSessionConfiguration.af.default
   
        configuration.httpCookieStorage = HTTPCookieStorage.shared
        
        var cookie = [HTTPCookiePropertyKey : Any]()
        cookie[HTTPCookiePropertyKey.name] = "ss"
        cookie[HTTPCookiePropertyKey.value] = "sss"
        cookie[HTTPCookiePropertyKey.domain] = host
        cookie[HTTPCookiePropertyKey.path] = "/"
        if let cool =   HTTPCookie(properties: cookie) {
            configuration.httpCookieStorage?.setCookie(cool)
        }
        
        let session = Session(configuration: configuration, serverTrustManager: manager)
        self.mSession = session
        let request =   session.request(urlStr)
        request.responseString { response in
            self.mSession = nil
            if let error = response.error {
                print(error.errorDescription)
            } else if let str = response.value {
                print(str)
            }
        }
        
//        session.download(resumingWith: Data()) { temporaryURL, response in
//            return (temporaryURL, [.delete])
//        }
      
//        let dest = getDesition(nil, fileName: nil)
//        let request: DownloadRequest = AF.download("http://172.16.11.28:8080/file/test.png", to: dest)
//        request.responseString { response in
//            response.response?.statusCode
//
//        }
        

        
    }
    
    func test() {
        // 定义你的私有证书
//        let serverTrustPolicies: [String: ServerTrustPolicy] = [
//            "your-private-domain.com": .performRevocationCheck(.none)
//        ]
//
//        // 创建ServerTrustPolicyManager实例
//        let serverTrustPolicyManager = ServerTrustPolicyManager(policies: serverTrustPolicies)
//
//        // 创建SessionManager实例，使用自定义的ServerTrustPolicyManager
//        let sessionManager = Alamofire.SessionManager(
//            serverTrustPolicyManager: serverTrustPolicyManager
//        )
//
//        // 使用自定义的SessionManager进行网络请求
//        sessionManager.request("https://your-private-domain.com").response { response in
//            debugPrint(response)
//        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

